
//Copyright 1997-2009 Syrinx Development, Inc.
//This file is part of the Syrinx Web Application Framework (SWAF).
// == BEGIN LICENSE ==
//
// Licensed under the terms of any of the following licenses at your
// choice:
//
//  - GNU General Public License Version 3 or later (the "GPL")
//    http://www.gnu.org/licenses/gpl.html
//
//  - GNU Lesser General Public License Version 3 or later (the "LGPL")
//    http://www.gnu.org/licenses/lgpl.html
//
//  - Mozilla Public License Version 1.1 or later (the "MPL")
//    http://www.mozilla.org/MPL/MPL-1.1.html
//
// == END LICENSE ==
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Web.UI;
using System.Xml;

using Swaf;
using Swaf.Gui;

namespace Swaf.Gui.AspNet2
{
	[ParseChildren(false)]
	public class BizProc : System.Web.UI.UserControl
	{
		protected ActiveBizProc m_bizproc = null;
		protected string m_innerXml = null;
		protected string m_factoryName = null;

		public BizProcEvent BizProcCreated = null;

		protected override void OnLoad(EventArgs e)
		{
			base.OnLoad(e);

            getActiveBizProc();

		}

        protected ActiveBizProc getActiveBizProc()
        {
            if (m_bizproc == null)
            {
                if (!IsPostBack && Page is BasePage || BPC.getBizProcOfflineState(ID) == null)
                    setupState(m_innerXml);
                m_bizproc = BPC.getActiveBizProc(ID);
                m_bizproc.CreatedFromPage = true;
                if (!IsPostBack)
                    m_bizproc.ForceShowBizObj = true;

                if (BizProcCreated != null)
                    BizProcCreated(this);
            }
            return m_bizproc;
        }

		protected override void AddParsedSubObject(object obj)
		{
			LiteralControl control = obj as LiteralControl;
			if (control != null)
				m_innerXml = control.Text; 
		}

		public string OrigionalInnerState { get { return m_innerXml; } }

		public void setupState(string xml)
		{
			XmlDocument doc = new XmlDocument();
			doc.LoadXml(string.Format("<BizProc>{0}</BizProc>", xml));
			State.processOfflineState(doc.DocumentElement);
			State.FactoryName = m_factoryName;
		}

		protected BizProcOfflineState State
		{
			get
			{
				BizProcOfflineState state = BPC.getBizProcOfflineState(ID);
				if (state == null)
					BPC.addBizProcOfflineState(state = new BizProcOfflineState(ID));
				return state;
			}
		}

		public BizProcCoordinator BPC
		{
			get { return (Page is IPage) ? ((IPage)Page).BPC : null; }
		}

		public IBusinessProcess TheBizProc
		{
			get
			{
				return getActiveBizProc().BizProc;
			}
		}

		public string FactoryName
		{
			get { return m_factoryName; }
			set { m_factoryName = value; }
		}
	}
}
